package com.hertz.iris.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.LabeledIntent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

import com.hertz.iris.IrisApplication;
import com.hertz.iris.IrisServiceProvider;
import com.hertz.iris.MyHttpException;
import com.hertz.iris.R;
import com.hertz.iris.authenticator.OpenIdTokenProvider;
import com.hertz.iris.dao.MatchAlarmDao;
import com.hertz.iris.pojo.MatchAlarm;
import com.hertz.iris.pojo.MatchNba;
import com.hertz.iris.pojo.ResponseIsAlert;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.Ln;
import com.hertz.iris.util.Strings;
import com.hertz.iris.view.alert.MatchAlarmRec;

public class MatchAlarmService {
	@Inject IrisServiceProvider serviceProvider;
	@Inject OpenIdTokenProvider openidTokenProvider;
	@Inject
	public MatchAlarmService(){}
	
	public List<MatchNba> getMatchsNba(Activity activity,String ymd) throws IOException{
		List<MatchNba> list = null;
		try {
			list = serviceProvider.getService(activity).getMatchsNBA(ymd);
		} catch (MyHttpException mhe) {
			if(mhe.getCode() == Constants.Http.HTTP_CODE_403)
				openidTokenProvider.clearOpenIdTokenAndGotoIndex(activity);
			else
				throw new IOException("Unexpected response code: " + mhe.getCode());
		}
		return list;
	}
	
	
	public List<MatchAlarm> getMatchAlarms(Activity activity,String ymd) throws IOException{
		List<MatchAlarm> list = null;
		try {
			list = serviceProvider.getService(activity).getMatchAlarms(ymd);
		} catch (MyHttpException mhe) {
			if(mhe.getCode() == Constants.Http.HTTP_CODE_403)
				openidTokenProvider.clearOpenIdTokenAndGotoIndex(activity);
			else
				throw new IOException("Unexpected response code: " + mhe.getCode());
		}
		return list;
	}
	
	public boolean syncData(int days,Activity activity) throws IOException{
		boolean result = false;
		try {
			List<MatchAlarm> list = serviceProvider.getService(activity).getSyncData(days);
			if(list != null){
				if(list.size() != 0){
					DBService.getInstance().deleteAllMatchAlarm();
					DBService.getInstance().saveMatchAlarmLists(list);
					long currentTime = System.currentTimeMillis();
					for(MatchAlarm ma : list){
						if(ma.getStatus() == Constants.MATCH_ALARM.STATUS_UNALERM){
							long matchTime = ma.getMatchTime();
			        		if(currentTime > matchTime){
			        			createMatchAlarmTrigger(ma, currentTime + Constants.DEFAULT_INTERVAL);
			        		}else{
			        			createMatchAlarmTrigger(ma, matchTime);
			        		}
						}
					}
				}
			}
			result = true;
		} catch (MyHttpException mhe) {
			if(mhe.getCode() == Constants.Http.HTTP_CODE_403)
				openidTokenProvider.clearOpenIdTokenAndGotoIndex(activity);
			else
				throw new IOException("Unexpected response code: " + mhe.getCode());
		}
		
		return result;
	}
	public boolean cancelMatchAlarmTrigger(MatchAlarm matchAlarm){
		AlarmManager am = (AlarmManager) IrisApplication.getInstance().getSystemService(Context.ALARM_SERVICE);  
        Intent intent = new Intent(Constants.MATCH_ALARM_ACTION);  
        intent.setClass(IrisApplication.getInstance().getApplicationContext(), MatchAlarmRec.class);  
        intent.putExtra(MatchAlarmDao.TABLENAME,matchAlarm);
        PendingIntent sender = PendingIntent.getBroadcast(IrisApplication.getInstance().getApplicationContext(), Long.valueOf(matchAlarm.getMid()).intValue(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        am.cancel(sender);
    	Ln.d("iris", String.format("cancel alarm,mid %d",matchAlarm.getMid()));
    	return true;
	}
	/*
	 * save or update,nextAlarmTime == 0,use matchAlarm.matchTime
	 */
	public boolean createMatchAlarmTrigger(MatchAlarm matchAlarm,long nextAlarmTime){
		if(nextAlarmTime == 0)
			nextAlarmTime = matchAlarm.getMatchTime();
		if(nextAlarmTime <= System.currentTimeMillis() - Constants.DEFAULT_INTERVAL)
			nextAlarmTime = System.currentTimeMillis() + Constants.DEFAULT_INTERVAL;
    	if(nextAlarmTime != 0 && nextAlarmTime > System.currentTimeMillis()){
        	AlarmManager am = (AlarmManager) IrisApplication.getInstance().getSystemService(Context.ALARM_SERVICE);  
            Intent intent = new Intent(Constants.MATCH_ALARM_ACTION);  
            intent.setClass(IrisApplication.getInstance().getApplicationContext(), MatchAlarmRec.class);  
            intent.putExtra(MatchAlarmDao.TABLENAME,matchAlarm);
			PendingIntent sender = PendingIntent.getBroadcast(IrisApplication
					.getInstance().getApplicationContext(),
					Long.valueOf(matchAlarm.getMid()).intValue(), intent,
					PendingIntent.FLAG_UPDATE_CURRENT);
            
            am.set(AlarmManager.RTC_WAKEUP, nextAlarmTime, sender); 
        	Ln.d("iris", String.format("next alarm time %d",nextAlarmTime));
        	return true;
    	}else{
    		return false;
    	}	
    }
	
	public void createNotication(ResponseIsAlert ria,Context context){
		Bitmap icon = BitmapFactory.decodeResource(context.getResources(),R.drawable.iris);
		long[] pattern = {500,500,500,500};
		Uri alarmSound = Strings.isBlank(ria.getIrisNbaAlarm().getRingUri()) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) : Uri.parse(ria.getIrisNbaAlarm().getRingUri());
		String message = ria.getMatchNba().getHostScore() + ":" + ria.getMatchNba().getGuestScore() + " " + ria.getMatchNba().getStatus();
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.iris)
                .setContentTitle(ria.getHostTeam().getTeamName() + "VS" + ria.getGuestTeam().getTeamName())
                .setContentText(message)
                .setSound(alarmSound);
        if(ria.getIrisNbaAlarm().getWave()){
        	mBuilder.setVibrate(pattern);
        }
        mBuilder.setTicker(message);//第一次提示消息的时候显示在通知栏上
//        mBuilder.setNumber(12);
        mBuilder.setLargeIcon(icon);
        mBuilder.setAutoCancel(true);//自己维护通知的消失
        
        
        //share
        Intent intent = shareIntent(context,ria);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(Long.valueOf(ria.getMatchNba().getId()).intValue(), mBuilder.build());
	}
	
	private Intent shareIntent(Context context,ResponseIsAlert ria){
		Intent it = new Intent(Intent.ACTION_SEND);
        it.setType("text/plain");
        List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(it, 0);
        if (!resInfo.isEmpty()) {
        	List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
            for (ResolveInfo info : resInfo) {
                Intent targeted = new Intent(Intent.ACTION_SEND);
                targeted.setType("text/plain");
                ActivityInfo activityInfo = info.activityInfo;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                // judgments : activityInfo.packageName, activityInfo.name, etc.
                String packageName = activityInfo.packageName;
                if (packageName.contains("tencent") 
                		|| packageName.contains("sina") 
                		|| packageName.contains("renren")
                		|| packageName.contains("weico")) {
					targeted.putExtra(Intent.EXTRA_TEXT, String.format(
							Constants.SHARE_CONTENT_TEMPLATE, ria.getHostTeam()
									.getTeamName(), ria.getGuestTeam()
									.getTeamName(), ria.getMatchNba()
									.getHostScore(), ria.getMatchNba()
									.getGuestScore()));
                    targeted.putExtra(Intent.EXTRA_SUBJECT, Constants.SHARE_TITLE);
                    targeted.setComponent(new ComponentName(packageName, activityInfo.name));
                    targeted.setPackage(packageName);
                    intentList.add(new LabeledIntent(targeted, packageName, info.loadLabel(context.getPackageManager()), activityInfo.icon));
                }
            }
            if (intentList == null || intentList.size() == 0) {
                return null;
            }
            // A Parcelable[] of Intent or LabeledIntent objects as set with
            // putExtra(String, Parcelable[]) of additional activities to place
            // a the front of the list of choices, when shown to the user with a
            // ACTION_CHOOSER.
            Intent chooserIntent = Intent.createChooser(intentList.remove(0), "请选择1");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray( new LabeledIntent[ intentList.size() ]));
            return chooserIntent;
        }
        return null;
	}
	
	/*
	 * intervale value or alarms
	 * integer or List<ResponseIsAlert>
	 */
	
	
	public ResponseIsAlert getAlert(Context context,long mid) throws Exception{
		ResponseIsAlert responseIsAlert = null;
		try {
			responseIsAlert = serviceProvider.getService(context).isAlert(mid);
		}  catch (MyHttpException mhe) {
			if(mhe.getCode() == Constants.Http.HTTP_CODE_403)
				openidTokenProvider.clearOpenIdToken(context);
			else
				throw new IOException("Unexpected response code: " + mhe.getCode());
		}
		return responseIsAlert;
	}
	
	public boolean saveOrUpdateMatchAlarm(MatchAlarm matchAlarm,Activity activity) throws Exception{
		boolean result = false;
		try {
			result = serviceProvider.getService(activity).postMatchAlarm(matchAlarm);
			if(result){
				long localId = DBService.getInstance().saveMatchAlarm(matchAlarm);
				if(localId > 0){
					return createMatchAlarmTrigger(matchAlarm,0);
				}
				result = true;
			}else
				result = false;
		} catch (MyHttpException mhe) {
			if(mhe.getCode() == Constants.Http.HTTP_CODE_403)
				openidTokenProvider.clearOpenIdTokenAndGotoIndex(activity);
			else
				throw new IOException("Unexpected response code: " + mhe.getCode());
		}
		
		return result;
	}
	
	public boolean cancelMatchAlarm(MatchAlarm matchAlarm,Activity activity) throws IOException{
		boolean result = false;
		try {
			if(serviceProvider.getService(activity).cancelMatchAlarm(matchAlarm.getMid())){
				DBService.getInstance().deleteMatchAlarm(matchAlarm);
				cancelMatchAlarmTrigger(matchAlarm);
				result = true;
			}
		} catch (MyHttpException mhe) {
			if(mhe.getCode() == Constants.Http.HTTP_CODE_403)
				openidTokenProvider.clearOpenIdTokenAndGotoIndex(activity);
			else
				throw new IOException("Unexpected response code: " + mhe.getCode());
		}
		return result;
	}
	
	public boolean SaveOrUpdateToLocal(MatchAlarm ma){
		long id = DBService.getInstance().saveMatchAlarm(ma);
		if(id > 0)
			return true;
		else
			return false;
	}
	
	public List<MatchAlarm> getMatchAlarmFromLocalByStatus(byte status){
		return DBService.getInstance().loadMatchAlarmByStatus(status);
	}
	
	public MatchAlarm getMatchAlarmFromLocal(long mid){
		return DBService.getInstance().loadMatchAlarmByMid(mid);
	}
	
//	public void resetAlarmActive(MatchAlarm matchAlarm){
//		DBService.getInstance().saveMatchAlarm(matchAlarm);
//    	AlarmManager am = (AlarmManager) IrisApplication.getInstance().getApplicationContext().getSystemService(Context.ALARM_SERVICE);  
//        Intent intent = new Intent(Constants.MATCH_ALARM_ACTION);  
//        intent.setClass(IrisApplication.getInstance().getApplicationContext(), MatchAlarmRec.class);  
//        intent.putExtra(MatchAlarmDao.TABLENAME,matchAlarm);
//        Integer ymd = Integer.valueOf(matchAlarm.getMatchTime().split(" ")[0].replaceAll("-", ""));
//        PendingIntent sender = PendingIntent.getBroadcast(IrisApplication.getInstance().getApplicationContext(), ymd, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//        long nextAlarmTime = DateUtil.string2Time(matchAlarm.getMatchTime(),DateUtil.YMD_HM);
//        am.set(AlarmManager.RTC_WAKEUP, nextAlarmTime, sender); 
//    }
}
